package com.lc.parser;

import com.lc.action.MyServlet;
import com.lc.adapter.HttpAdapter;
import com.lc.config.Configuration;
import com.lc.mapper.*;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.FileInputStream;
import java.util.List;
import java.util.Set;

/**
 * @author liuc
 * @date 2021/5/9
 * @description
 **/
public class WebXmlParser {

    private File file;
    private Context context;
    private Set<Class> set;

    public WebXmlParser(File file, Context context, Set<Class> set){
        this.file = file;
        this.context = context;
        this.set = set;
    }
    public void parse(){
        //解析web.xml
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(new FileInputStream(file));
            Element rootElement = document.getRootElement();
            //拿到service标签
            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element =  selectNodes.get(i);
                Element servletNameTag = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletNameTag.getStringValue();
                Element servletClassTag = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletClassTag.getStringValue();
                //todo matchClass
                Class clz = matchClass(set,servletClass);
                if(clz == null){
                    continue;
                }
                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                HttpServlet httpServlet = (HttpServlet) clz.newInstance();
                Wrapper wrapper = new Wrapper(urlPattern,httpServlet);
                context.addWrapper(wrapper);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Class matchClass(Set<Class> classes, String className){
        for (Class aClass : classes) {
            if(aClass.getName().equals(className)){
                return aClass;
            }
        }
        return null;
    }
}
